package com.example.studentportrait.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.studentportrait.domain.ResponseResult;
import com.example.studentportrait.domain.dto.ListAssessmentQuestionDto;
import com.example.studentportrait.domain.entity.AssessmentQuestion;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.studentportrait.domain.vo.PageVo;
import com.example.studentportrait.enums.AppHttpCodeEnum;
import com.example.studentportrait.exception.SystemException;
import com.example.studentportrait.mapper.AssessmentQuestionMapper;
import com.example.studentportrait.service.AssessmentQuestionService;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import static com.example.studentportrait.enums.AppHttpCodeEnum.SYSTEM_ERROR;
import static java.sql.Types.BOOLEAN;
import static java.sql.Types.NUMERIC;
import static org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType.FORMULA;
import static org.apache.xmlbeans.impl.piccolo.xml.Piccolo.STRING;

@Service("assessmentQuestionService")
public class AssessmentQuestionlmpl extends ServiceImpl<AssessmentQuestionMapper, AssessmentQuestion> implements AssessmentQuestionService {
    @Autowired
    private AssessmentQuestionMapper assessmentQuestionMapper;

    @Override
    public ResponseResult assessmentQuestionlist(int pageNum, int size, ListAssessmentQuestionDto listAssessmentQuestionDto) {
        LambdaQueryWrapper<AssessmentQuestion> queryWrapper = new LambdaQueryWrapper<>();

        if (listAssessmentQuestionDto!=null) {
            // 根据题目名称进行模糊查询
            queryWrapper.like(StringUtils.hasText(listAssessmentQuestionDto.getTitle()), AssessmentQuestion::getTitle, listAssessmentQuestionDto.getTitle());
            // 根据题目类型进行相等查询
            queryWrapper.eq(StringUtils.hasText(listAssessmentQuestionDto.getType()), AssessmentQuestion::getQuestionType, listAssessmentQuestionDto.getType());
            // 根据assessment_id进行相等查询
            queryWrapper.eq(listAssessmentQuestionDto.getAssessmentId() != null, AssessmentQuestion::getAssessmentId, listAssessmentQuestionDto.getAssessmentId());
        }
        // 分页查询
        Page<AssessmentQuestion> page = new Page<>(pageNum, size);
        IPage<AssessmentQuestion> assessmentQuestionPage = assessmentQuestionMapper.selectPage(page, queryWrapper);

        // 获取查询结果
        List<AssessmentQuestion> assessmentQuestionList = assessmentQuestionPage.getRecords();

        // 返回分页结果
        PageVo pageVo = new PageVo(assessmentQuestionList, assessmentQuestionPage.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult addAssessmentQuestion(AssessmentQuestion assessmentQuestion) {
        if (!StringUtils.hasText(assessmentQuestion.getQuestionContent()) || assessmentQuestion.getAnswer() == null) {
            throw new SystemException(SYSTEM_ERROR);
        }
//       新增tag
        save(assessmentQuestion);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<AssessmentQuestion> updateAssessmentQuestion(AssessmentQuestion assessmentQuestion) {
        if ( assessmentQuestion.getId() == null) {
            throw new SystemException(AppHttpCodeEnum.ID_NOT_NULL);
        }
        // 构建 UpdateWrapper
        UpdateWrapper<AssessmentQuestion> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", assessmentQuestion.getId());

        // 只更新非 null 的字段
        if (assessmentQuestion.getAssessmentId() != null) {
            updateWrapper.set("assessment_id", assessmentQuestion.getAssessmentId());
        }
        if (assessmentQuestion.getTitle() != null) {
            updateWrapper.set("title", assessmentQuestion.getTitle());
        }
        if (assessmentQuestion.getQuestionContent() != null) {
            updateWrapper.set("question_content", assessmentQuestion.getQuestionContent());
        }
        if (assessmentQuestion.getQuestionType() != null) {
            updateWrapper.set("question_type", assessmentQuestion.getQuestionType());
        }
        if (assessmentQuestion.getOption1() != null) {
            updateWrapper.set("option_1", assessmentQuestion.getOption1());
        }
        if (assessmentQuestion.getOption2() != null) {
            updateWrapper.set("option_2", assessmentQuestion.getOption2());
        }
        if (assessmentQuestion.getOption3() != null) {
            updateWrapper.set("option_3", assessmentQuestion.getOption3());
        }
        if (assessmentQuestion.getOption4() != null) {
            updateWrapper.set("option_4", assessmentQuestion.getOption4());
        }
        if (assessmentQuestion.getAnswer() != null) {
            updateWrapper.set("answer", assessmentQuestion.getAnswer());
        }
        if (assessmentQuestion.getDifficultyLevel() != null) {
            updateWrapper.set("difficulty_level", assessmentQuestion.getDifficultyLevel());
        }
        if (assessmentQuestion.getCreateTime() != null) {
            updateWrapper.set("create_time", assessmentQuestion.getCreateTime());
        }
        if (assessmentQuestion.getUpdateTime() != null) {
            updateWrapper.set("update_time", assessmentQuestion.getUpdateTime());
        }
        if (assessmentQuestion.getCreateUser() != null) {
            updateWrapper.set("create_user", assessmentQuestion.getCreateUser());
        }
        if (assessmentQuestion.getUpdateUser() != null) {
            updateWrapper.set("update_user", assessmentQuestion.getUpdateUser());
        }
        System.out.println(assessmentQuestion);
        // 执行更新操作
        boolean updated = update(updateWrapper);
        if (!updated) {
            throw new SystemException(SYSTEM_ERROR);
        }
        return ResponseResult.okResult(assessmentQuestion); // 返回更新后的对象
    }

    @Override
    public ResponseResult deleteAssessmentQuestion(Integer id) {
        if (Objects.nonNull(id) && id > 0) {
            boolean removed = removeById(id);
            if (!removed) {
                throw new SystemException(SYSTEM_ERROR);
            }
        } else {
            throw new SystemException(AppHttpCodeEnum.ID_NOT_NULL);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteAssessmentQuestions(List<Integer> ids) {
        // 使用 MyBatis-Plus 的 removeByIds 方法来批量删除
        boolean result = removeByIds(ids);

        if (result) {
            return ResponseResult.okResult("题目删除成功");
        } else {
            throw new SystemException(AppHttpCodeEnum.ANNOUNCEMENT_DELETE_FAIL);
        }
    }

    @Override
    public ResponseResult insertAssessmentQuestionListByExcel(MultipartFile file) {
        try (InputStream excelFile = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(excelFile)) {

            // User user = userMapper.selectById(userId);
            // if (user.getRoleId() != 2) {
            // return Result.build(null, 504, "Have no permission");
            // }
            List<AssessmentQuestion> assessmentQuestions = new ArrayList<>();

            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            // 跳过第一行
            if (rowIterator.hasNext()) {
                rowIterator.next();
            }

            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                List<String> cellValues = new ArrayList<>();

                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    if (cell == null) {
                        cellValues.add("");
                    } else {
                        switch (cell.getCellTypeEnum()) {
                            case STRING:
                                cellValues.add(cell.getStringCellValue());
                                break;
                            case NUMERIC:
                                cellValues.add(String.valueOf(cell.getNumericCellValue()));
                                break;
                            default:
                                cellValues.add(""); // 处理其他类型或未知类型
                        }
                    }
                }
                // 检查并处理空字符串
                AssessmentQuestion assessmentQuestion = new AssessmentQuestion();
                if (!cellValues.get(0).isEmpty()) {
                    assessmentQuestion.setAssessmentId((int) Double.parseDouble(cellValues.get(0)));
                }
                assessmentQuestion.setTitle(cellValues.get(1));
                assessmentQuestion.setQuestionContent(cellValues.get(2));
                assessmentQuestion.setQuestionImage(cellValues.get(3));
                if (!cellValues.get(4).isEmpty()) {
                    assessmentQuestion.setQuestionType(String.valueOf((int) Double.parseDouble(cellValues.get(4))));
                }
                assessmentQuestion.setOption1(cellValues.get(5));
                assessmentQuestion.setOption2(cellValues.get(6));
                assessmentQuestion.setOption3(cellValues.get(7));
                assessmentQuestion.setOption4(cellValues.get(8));
                assessmentQuestion.setAnswer(cellValues.get(9));
                if (!cellValues.get(10).isEmpty()) {
                    assessmentQuestion.setDifficultyLevel((int) Double.parseDouble(cellValues.get(10)));
                }
//            questionBank.setIsDelete((int) Double.parseDouble(cellValues.get(10)));
//            questionBank.setCreateUser("管理员批量导入");
//            questionBank.setUpdateUser("管理员批量导入");
                System.out.println("=========================================");
                System.out.println(assessmentQuestion);
                assessmentQuestions.add(assessmentQuestion);
            }

            for (AssessmentQuestion assessmentQuestion : assessmentQuestions) {
                save(assessmentQuestion);
//                assessmentQuestionMapper.insert(assessmentQuestion);
            }

            return ResponseResult.okResult("题目添加成功！！！！");
        } catch (Exception exception) {
            log.error("Error:" + exception);
            return ResponseResult.errorResult(SYSTEM_ERROR);
        }
    }



}